/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.buanalintas.sandals.pos.purchaseorderdetail;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Operator;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpSession;

/**
 *
 * @author user
 */
public class ListTransaction {

    public static StringBuffer process(Page page) {
        return process(page, null);
    }

    public static StringBuffer process(Page page, Template template) {
        HttpSession session = page.getRequest().getSession();
        if (template == null) {
            template = new Template("trans-list.html");
        }

        doAction(page);

        template.addValue(Template.TABLE_JAVASCRIPT, "<script type=\"text/javascript\" src=\"?file=list.js\"></script>" + page.addJavascript());

        template.addValue(Template.TABLE_FORM_NAME, "form-" + page.getMenu().getMenuId());
        template.addValue(Template.TABLE_FORM_TARGET, "_self");
        template.addValue(Template.TABLE_FORM_ACTION, "?m=" + page.getMenu().getMenuName() + "&a=" + Action.TRANS_DETAIL_LIST.getName());

        StringBuffer command = template.getEmptyElement(Template.TABLE_COMMANDS);

        StringBuffer commands = new StringBuffer();
        StringBuffer commandAdd = template.getEmptyElement(Template.TABLE_COMMANDS_COMMAND_ADD);
        Utility.replaceAll(commandAdd, Template.TABLE_COMMANDS_COMMAND_ADD_LINK, "?m=" + page.getMenu().getMenuName() + "&supplier='+parent.document.getElementById('purchaseOrderSupplierId').value+'&a=" + Action.TRANS_DETAIL_ADD.getName());
        Utility.replaceAll(commandAdd, Template.TABLE_COMMANDS_COMMAND_ADD_TITLE, Dictionary.getValue(page, "New"));
        Utility.replaceAll(commandAdd, Template.TABLE_COMMANDS_COMMAND_ADD_PROPERTIES, "");
        commands.append(!page.isGranted(Action.TRANS_DETAIL_ADD) ? "" : commandAdd.toString());

        StringBuffer commandDelete = template.getEmptyElement(Template.TABLE_COMMANDS_COMMAND_DELETE);
        Utility.replaceAll(commandDelete, Template.TABLE_COMMANDS_COMMAND_DELETE_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + Action.TRANS_DETAIL_LIST.getName());
        Utility.replaceAll(commandDelete, Template.TABLE_COMMANDS_COMMAND_DELETE_TITLE, Dictionary.getValue(page, "Delete"));
        Utility.replaceAll(commandDelete, Template.TABLE_COMMANDS_COMMAND_DELETE_NAME, "form-" + page.getMenu().getMenuId());
        Utility.replaceAll(commandDelete, Template.TABLE_COMMANDS_COMMAND_DELETE_PROPERTIES, " onclick=\"return __deleteMultiple('" + "?m=" + page.getMenu().getMenuName() + "&a=" + Action.TRANS_DETAIL_LIST.getName() + "', 'form-" + page.getMenu().getMenuId() + "')\"");
        commands.append(!page.isGranted(Action.DELETE_MULTI) ? "" : commandDelete.toString());

        commands.append(page.processCustomCommand(template.getEmptyElement(Template.TABLE_COMMANDS_COMMAND_CUSTOM), page).toString());

        Utility.replaceAll(command, template.getElement(Template.TABLE_COMMANDS_COMMAND).toString(), commands.toString());
        template.addElement(Template.TABLE_COMMANDS, command);

        template.addElement(Template.TABLE_TITLE_MENU);
        template.addElement(Template.TABLE_TITLE_CHECK);
        template.addElement(Template.TABLE_TITLE_NO);

        StringBuffer titleTd = new StringBuffer();
        for (Field f : page.getFieldsList()) {
            StringBuffer titleTds = template.getEmptyElement(Template.TABLE_TITLE_TD);
            Utility.replaceAll(titleTds, Template.TABLE_TITLE_TD_SPAN_PROPERTIES, "");
            Utility.replaceAll(titleTds, Template.TABLE_TITLE_TD_PROPERTIES, f.getListProperties());
            Utility.replaceAll(titleTds, Template.TABLE_TITLE_TD_TEXT, Utility.upperCaseFirstWords(Dictionary.getValue(page, f.getCaption())));
            titleTd.append(titleTds);
        }
        template.addElement(Template.TABLE_TITLE_TD, titleTd);
        int number = 0;
        try {
            StringBuffer rowsTd = new StringBuffer();
            if (session.getAttribute("transactions") == null) {
                session.setAttribute("transactions", new ArrayList());
            }
            List datas = (List) session.getAttribute("transactions");
            if (datas.size() > 0 && !datas.get(0).getClass().equals(page.getTheClass())) {
                datas.clear();
            }
            for (Object data : datas) {
                page.setCurrentData(data);
                number++;
                StringBuffer row = template.getEmptyElement(Template.TABLE_ROW);

                StringBuffer rowMenu = template.getEmptyElement(Template.TABLE_ROW_MENU);

                StringBuffer rowMenuCommand = template.getEmptyElement(Template.TABLE_ROW_MENU_COMMAND);

                StringBuffer rowMenuCommandEdit = template.getEmptyElement(Template.TABLE_ROW_MENU_COMMAND_EDIT);
                Utility.replaceAll(rowMenuCommandEdit, Template.TABLE_ROW_MENU_COMMAND_EDIT_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + Action.TRANS_DETAIL_EDIT.getName() + "&supplier='+parent.document.getElementById('purchaseOrderSupplierId').value+'&id=" + Utility.encode("" + number));
                Utility.replaceAll(rowMenuCommandEdit, Template.TABLE_ROW_MENU_COMMAND_EDIT_TITLE, Dictionary.getValue(page, "Edit"));
                Utility.replaceAll(rowMenuCommandEdit, Template.TABLE_ROW_MENU_COMMAND_EDIT_PROPERTIES, "");
                Utility.replaceAll(rowMenuCommand, template.getElement(Template.TABLE_ROW_MENU_COMMAND_EDIT).toString(), !page.isGranted(Action.TRANS_DETAIL_EDIT, data) ? "" : rowMenuCommandEdit.toString());

                StringBuffer rowMenuCommandDelete = template.getEmptyElement(Template.TABLE_ROW_MENU_COMMAND_DELETE);
                Utility.replaceAll(rowMenuCommandDelete, Template.TABLE_ROW_MENU_COMMAND_DELETE_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + Action.TRANS_DETAIL_LIST.getName() + "&delete=" + Utility.encode("" + number));
                Utility.replaceAll(rowMenuCommandDelete, Template.TABLE_ROW_MENU_COMMAND_DELETE_TITLE, Dictionary.getValue(page, "Delete"));
                Utility.replaceAll(rowMenuCommandDelete, Template.TABLE_ROW_MENU_COMMAND_DELETE_PROPERTIES, " onclick=\"return __deleteDetail('" + "?m=" + page.getMenu().getMenuName() + "&a=" + Action.TRANS_DETAIL_LIST.getName() + "&delete=" + number + "'\"");
                Utility.replaceAll(rowMenuCommand, template.getElement(Template.TABLE_ROW_MENU_COMMAND_DELETE).toString(), !page.isGranted(Action.DELETE, data) ? "" : rowMenuCommandDelete.toString());

                Utility.replaceAll(rowMenuCommand, template.getElement(Template.TABLE_ROW_MENU_COMMAND_CUSTOM).toString(), page.processCustomRowCommand(template.getEmptyElement(Template.TABLE_ROW_MENU_COMMAND_CUSTOM), page, data).toString());

                Utility.replaceAll(rowMenu, template.getElement(Template.TABLE_ROW_MENU_COMMAND).toString(), rowMenuCommand.toString());
                Utility.replaceAll(row, template.getElement(Template.TABLE_ROW_MENU).toString(), rowMenu.toString());

                StringBuffer rowCheck = template.getEmptyElement(Template.TABLE_ROW_CHECK);
                Utility.replaceAll(rowCheck, Template.TABLE_ROW_CHECK_CHECKED, "");
                Utility.replaceAll(rowCheck, Template.TABLE_ROW_CHECK_VALUE, "" + Utility.encode("" + number));
                Utility.replaceAll(row, template.getElement(Template.TABLE_ROW_CHECK).toString(), rowCheck.toString());

                StringBuffer rowNo = template.getEmptyElement(Template.TABLE_ROW_NO);
                Utility.replaceAll(rowNo, Template.TABLE_ROW_NO_PROPERTIES, "");
                Utility.replaceAll(rowNo, Template.TABLE_ROW_NO_TEXT, "" + number);
                Utility.replaceAll(row, template.getElement(Template.TABLE_ROW_NO).toString(), rowNo.toString());

                Utility.replaceAll(row, Template.TABLE_ROW_CLASS, number % 2 == 0 ? "2" : "1");
                Utility.replaceAll(row, Template.TABLE_ROW_VALUE, "" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));

                rowsTd.delete(0, rowsTd.length());
                for (Field f : page.getFieldsList()) {
                    StringBuffer rowsTds = template.getEmptyElement(Template.TABLE_ROW_TD);
                    Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_PROPERTIES, f.getListProperties());
                    if (!f.getOptions().isEmpty()) {
                        StringBuffer val = new StringBuffer(Utility.getStringValue(data, f));
                        for (String[] v : f.getOptions()) {
                            Utility.replaceAll(val, v[0], Dictionary.getValue(page, v[1]));
                        }
                        Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_TEXT, f.getFormater() == null ? val.toString() : f.getFormater().format(val));
                    } else {
                        Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_TEXT, f.getFormater() == null ? Utility.getStringValue(data, f) : f.getFormater().format(Utility.getValue(data, f)));
                    }
                    Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_VALUE, Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                    rowsTd.append(rowsTds);
                }
                Utility.replaceAll(row, template.getElement(Template.TABLE_ROW_TD).toString(), rowsTd.toString());
                template.addRepeat(Template.TABLE_ROW, row);
            }
            if (datas.isEmpty()) {
                template.addElement(Template.TABLE_ROW, null);
            }
        } catch (Exception e) {
        }

        StringBuffer hidden = new StringBuffer();
        StringBuffer hiddenAction = template.getEmptyElement(Template.TABLE_HIDDEN_ACTION);
        Utility.replaceAll(hiddenAction, Template.TABLE_HIDDEN_ACTION_VALUE, "");
        hidden.append(hiddenAction.toString());
        StringBuffer hiddenConfirm = template.getEmptyElement(Template.TABLE_HIDDEN_CONFIRM);
        Utility.replaceAll(hiddenConfirm, Template.TABLE_HIDDEN_CONFIRM_VALUE, "");
        hidden.append(hiddenConfirm.toString());
        template.addElement(Template.TABLE_HIDDEN, hidden);

        return template.process();
    }

    public static StringBuffer list(Page page) {
        Template template = new Template("trans-view.html");

        template.addElement(Template.TABLE_TITLE_NO);
        Page detail = null;
        try {
            detail = page.getDetail();
        } catch (Exception e) {
        }

        StringBuffer titleTd = new StringBuffer();
        for (Field f : detail.getFieldsList()) {
            StringBuffer titleTds = template.getEmptyElement(Template.TABLE_TITLE_TD);
            Utility.replaceAll(titleTds, Template.TABLE_TITLE_TD_SPAN_PROPERTIES, "");
            Utility.replaceAll(titleTds, Template.TABLE_TITLE_TD_PROPERTIES, f.getListProperties());
            Utility.replaceAll(titleTds, Template.TABLE_TITLE_TD_TEXT, Utility.upperCaseFirstWords(Dictionary.getValue(page, f.getCaption())));
            titleTd.append(titleTds);
        }
        template.addElement(Template.TABLE_TITLE_TD, titleTd);
        int number = 0;
        try {
            StringBuffer rowsTd = new StringBuffer();
            List datas = new ArrayList();
            String id = Utility.decode(Utility.getPostParameter(page, "id"));
            if (id != null && !id.equals("")) {
                Object data = page.getController().getData(id);
                detail.getController().setWhere("t." + Utility.getForeignKeyField(detail.getTheClass(), data) + "." + Utility.getPrimaryKeyField(data.getClass()) + "='" + Utility.getPrimaryKeyValue(data) + "'");
                datas = detail.getController().getData(true);
            }
            for (Object data : datas) {
                number++;
                StringBuffer row = template.getEmptyElement(Template.TABLE_ROW);

                StringBuffer rowNo = template.getEmptyElement(Template.TABLE_ROW_NO);
                Utility.replaceAll(rowNo, Template.TABLE_ROW_NO_PROPERTIES, "");
                Utility.replaceAll(rowNo, Template.TABLE_ROW_NO_TEXT, "" + number);
                Utility.replaceAll(row, template.getElement(Template.TABLE_ROW_NO).toString(), rowNo.toString());

                Utility.replaceAll(row, Template.TABLE_ROW_CLASS, number % 2 == 0 ? "2" : "1");
                Utility.replaceAll(row, Template.TABLE_ROW_VALUE, "" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));

                rowsTd.delete(0, rowsTd.length());
                for (Field f : detail.getFieldsList()) {
                    StringBuffer rowsTds = template.getEmptyElement(Template.TABLE_ROW_TD);
                    Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_PROPERTIES, f.getListProperties());
                    if (!f.getOptions().isEmpty()) {
                        String val = Utility.getStringValue(data, f);
                        for (String[] v : f.getOptions()) {
                            if (v[0].equals(val)) {
                                val = Dictionary.getValue(page, v[1]);
                                break;
                            }
                        }
                        Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_TEXT, f.getFormater() == null ? val : f.getFormater().format(val));
                    } else {
                        Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_TEXT, f.getFormater() == null ? Utility.getStringValue(data, f) : f.getFormater().format(Utility.getValue(data, f)));
                    }
                    Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_VALUE, Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                    rowsTd.append(rowsTds);
                }
                Utility.replaceAll(row, template.getElement(Template.TABLE_ROW_TD).toString(), rowsTd.toString());
                template.addRepeat(Template.TABLE_ROW, row);
            }
            if (datas.isEmpty()) {
                template.addElement(Template.TABLE_ROW, null);
            }
        } catch (Exception e) {
        }

        return template.process();
    }

    private static String doAction(Page page) {
        HttpSession session = page.getRequest().getSession();
        String delete = Utility.decode(Utility.getPostParameter(page, "delete"));
        String load = Utility.getPostParameter(page, "load");
        if (load != null && delete == null) {
            if (session.getAttribute("transactions") == null) {
                session.setAttribute("transactions", new ArrayList());
            }
            List datas = (List) session.getAttribute("transactions");
            page.loadDetail(datas, Utility.getPostParameter(page, "load"));
        }
        if (delete != null && !delete.trim().equals("")) {
            List datas = (List) session.getAttribute("transactions");
            try {
                if (session.getAttribute("transactionsd") == null) {
                    session.setAttribute("transactionsd", new ArrayList());
                }
                ((List) session.getAttribute("transactionsd")).add(datas.get(Integer.parseInt(delete) - 1));
                datas.remove(Integer.parseInt(delete) - 1);
            } catch (Exception e) {
            }
        }
        if ("delete".equals(Utility.getPostParameter(page, "act")) && "yes".equals(Utility.getPostParameter(page, "confirm"))) {
            List datas = (List) session.getAttribute("transactions");
            try {
                if (session.getAttribute("transactionsd") == null) {
                    session.setAttribute("transactionsd", new ArrayList());
                }
                String[] uniqId = page.getRequest().getParameterValues("uniqId");
                for (String x : uniqId) {
                    String uid = Utility.decode(x);
                    Object deleted = datas.get(Integer.parseInt(uid) - 1);
                    page.getController().beforeDeleteDetail(deleted);
                    ((List) session.getAttribute("transactionsd")).add(deleted);
                    datas.remove(Integer.parseInt(uid) - 1);
                }
            } catch (Exception e) {
            }
        }
        return page.doAction();
    }

    public static boolean isValid(Page page, String column, String operator, String value) {
        Field f = page.getField(column);
        if (f != null) {
            if (isValid(f, operator, value)) {
                return true;
            }
        }
        return false;
    }

//    public static String createEntityCondition(Page page, String column, String operator, String value) {
//        Field f = page.getField(column);
//        if (f != null) {
//            if (isValid(f, operator, value)) {
//                return Operator.getOperator(operator).parse(column, Utility.quote(value));
//            }
//        }
//        return page.doAction();
//    }
    public static boolean isValid(Field f, String operator, String value) {
        // Integer, Double, Float, BigInteger, BigDecimal, Date, String
        boolean valid = false;
        try {
            if (f.getFieldType().equals(Integer.class)) {
                Integer.parseInt(value);
            } else if (f.getFieldType().equals(Double.class)) {
                Double.parseDouble(value);
            } else if (f.getFieldType().equals(Float.class)) {
                Float.parseFloat(value);
            } else if (f.getFieldType().equals(BigInteger.class)) {
                new BigInteger(value);
            } else if (f.getFieldType().equals(BigDecimal.class)) {
                new BigDecimal(value);
            } else if (f.getFieldType().equals(Date.class)) {
                f.getFormater().parse(value);
            }
            valid = true;
        } catch (Exception e) {
        }
        if (valid) {
            if (f.getFieldType().equals(Integer.class)
                    || f.getFieldType().equals(Double.class)
                    || f.getFieldType().equals(Float.class)
                    || f.getFieldType().equals(BigInteger.class)
                    || f.getFieldType().equals(BigDecimal.class)
                    || f.getFieldType().equals(Date.class)) {
                if (operator.equals(Operator.EQUALS.getName())
                        || operator.equals(Operator.LARGER.getName())
                        || operator.equals(Operator.LARGER_EQUALS.getName())
                        || operator.equals(Operator.NOT_EQUALS.getName())
                        || operator.equals(Operator.SMALLER.getName())
                        || operator.equals(Operator.SMALLER_EQUALS.getName())) {
                    return true;
                }
            } else if (f.getFieldType().equals(String.class)) {
                if (operator.equals(Operator.END_WITH.getName())
                        || operator.equals(Operator.EQUALS.getName())
                        || operator.equals(Operator.LIKE.getName())
                        || operator.equals(Operator.NOT_EQUALS.getName())
                        || operator.equals(Operator.NOT_LIKE.getName())
                        || operator.equals(Operator.START_WITH.getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    public static StringBuffer print(Page page) {
        Template template = new Template("print-list.html");

        template.addElement(Template.TABLE_TITLE_NO);
        Page detail = null;
        try {
            detail = page.getDetail();
        } catch (Exception e) {
        }
        if (detail == null) {
            return new StringBuffer();
        }
        StringBuffer titleTd = new StringBuffer();
        for (Field f : detail.getFieldsList()) {
            StringBuffer titleTds = template.getEmptyElement(Template.TABLE_TITLE_TD);
            Utility.replaceAll(titleTds, Template.TABLE_TITLE_TD_SPAN_PROPERTIES, "");
            Utility.replaceAll(titleTds, Template.TABLE_TITLE_TD_PROPERTIES, f.getListProperties());
            Utility.replaceAll(titleTds, Template.TABLE_TITLE_TD_TEXT, Utility.upperCaseFirstWords(Dictionary.getValue(page, f.getCaption())));
            titleTd.append(titleTds);
        }
        template.addElement(Template.TABLE_TITLE_TD, titleTd);
        int number = 0;
        try {
            StringBuffer rowsTd = new StringBuffer();
            List datas = new ArrayList();
            String id = Utility.decode(Utility.getPostParameter(page, "id"));
            if (id != null && !id.equals("")) {
                Object data = page.getController().getData(id);
                detail.getController().setWhere("t." + Utility.getForeignKeyField(detail.getTheClass(), data) + "." + Utility.getPrimaryKeyField(data.getClass()) + "='" + Utility.getPrimaryKeyValue(data) + "'");
                datas = detail.getController().getData(true);
            }
            for (Object data : datas) {
                number++;
                StringBuffer row = template.getEmptyElement(Template.TABLE_ROW);

                StringBuffer rowNo = template.getEmptyElement(Template.TABLE_ROW_NO);
                Utility.replaceAll(rowNo, Template.TABLE_ROW_NO_PROPERTIES, "");
                Utility.replaceAll(rowNo, Template.TABLE_ROW_NO_TEXT, "" + number);
                Utility.replaceAll(row, template.getElement(Template.TABLE_ROW_NO).toString(), rowNo.toString());

                Utility.replaceAll(row, Template.TABLE_ROW_CLASS, number % 2 == 0 ? "2" : "1");
                Utility.replaceAll(row, Template.TABLE_ROW_VALUE, "" + Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));

                rowsTd.delete(0, rowsTd.length());
                for (Field f : detail.getFieldsList()) {
                    StringBuffer rowsTds = template.getEmptyElement(Template.TABLE_ROW_TD);
                    Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_PROPERTIES, f.getListProperties());
                    if (!f.getOptions().isEmpty()) {
                        String val = Utility.getStringValue(data, f);
                        for (String[] v : f.getOptions()) {
                            if (v[0].equals(val)) {
                                val = Dictionary.getValue(page, v[1]);
                                break;
                            }
                        }
                        Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_TEXT, f.getFormater() == null ? val : f.getFormater().format(val));
                    } else {
                        Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_TEXT, f.getFormater() == null ? Utility.getStringValue(data, f) : f.getFormater().format(Utility.getValue(data, f)));
                    }
                    Utility.replaceAll(rowsTds, Template.TABLE_ROW_TD_VALUE, Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField())));
                    rowsTd.append(rowsTds);
                }
                Utility.replaceAll(row, template.getElement(Template.TABLE_ROW_TD).toString(), rowsTd.toString());
                template.addRepeat(Template.TABLE_ROW, row);
            }
            if (datas.isEmpty()) {
                template.addElement(Template.TABLE_ROW, null);
            }
        } catch (Exception e) {
        }

        return template.process();
    }
}